import cssModule from "@/style/login/login.module.scss";
import { Button, Checkbox, Col, Form, Input, Row } from "antd";
import { SafetyOutlined, UserOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import { getImgCode, login } from "@/api";
import { ImgCode, LoginForm } from "@/types/login";
import { CheckboxChangeEvent } from "antd/lib/checkbox";
import { useHistory, useLocation } from "react-router";
import { useDispatch } from "react-redux";
import { setTokenAction } from "@/redux/user/userReducer";
import { generateRoutes } from "@/redux/menus/menuReducer";
const REMEMBER_ME = "remember_me";
const Login: React.FC = () => {
    const [codeInfo, setCodeInfo] = useState<ImgCode>({
        key: "",
        svg: "",
    });
    const [loginForm, setLoginForm] = useState<LoginForm>({
        codeKey: "",
        code: "",
        username: "admin",
        password: "123456",
    });
    const [isRemember, setIsRemember] = useState(false);
    const [key, setKey] = useState(0);
    const [loading, setLoading] = useState(false);
    const history = useHistory();
    const location = useLocation();
    const dispatch = useDispatch();
    const refreshImgCode = () => {
        getImgCode().then(res => {
            setCodeInfo(res.data);
        });
    };
    useEffect(() => {
        loadStoreLoginInfo();
    }, []);
    const loadStoreLoginInfo = () => {
        const infoStr = localStorage.getItem(REMEMBER_ME);
        if (infoStr) {
            const info = JSON.parse(infoStr);
            setIsRemember(true);
            const value = {
                ...loginForm,
                username: info.username,
                password: info.password,
            };
            setLoginForm(value);
            form.setFieldsValue(value);
        }
    };
    const clearLoginInfo = () => {
        localStorage.removeItem(REMEMBER_ME);
    };
    const checkboxChange = (e: CheckboxChangeEvent) => {
        const checked = e.target.checked;
        setIsRemember(checked);
        if (!checked) {
            clearLoginInfo();
        }
    };
    const [form] = Form.useForm();
    const rememberme = () => {
        localStorage.setItem(
            REMEMBER_ME,
            JSON.stringify({
                username: loginForm.username,
                password: loginForm.password,
            })
        );
    };
    const submit = async () => {
        try {
            await form.validateFields();
            loginForm.codeKey = codeInfo.key;
            setLoading(true);
            const res = await login(loginForm);
            if (isRemember) {
                rememberme();
            }
            setTimeout(() => {
                dispatch(setTokenAction(res.data.token));
                dispatch(generateRoutes());
                history.push({ pathname: "/home" });
            }, 200);
        } finally {
            setLoading(false);
        }
    };
    useEffect(() => {
        refreshImgCode();
    }, []);
    return (
        <div className={cssModule.loginContainer}>
            <div className={cssModule.loginFormPanel}>
                <h2 className={cssModule.title}>react-antd-admin</h2>
                <div className={cssModule.formWrap}>
                    <Form form={form} autoComplete="off" key={key}>
                        <Form.Item
                            name="username"
                            rules={[
                                { required: true, message: "请输入用户名" },
                            ]}
                        >
                            <Input
                                size="large"
                                value={loginForm.username}
                                onChange={e =>
                                    setLoginForm({
                                        ...loginForm,
                                        username: e.target.value,
                                    })
                                }
                                prefix={<UserOutlined />}
                            />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            rules={[{ required: true, message: "请输入密码" }]}
                        >
                            <Input.Password
                                value={loginForm.password}
                                onChange={e =>
                                    setLoginForm({
                                        ...loginForm,
                                        password: e.target.value,
                                    })
                                }
                                size="large"
                                prefix={<SafetyOutlined />}
                            />
                        </Form.Item>
                        <Form.Item
                            name="code"
                            rules={[
                                { required: true, message: "请输入验证码" },
                            ]}
                        >
                            <div className={cssModule.codeItem}>
                                <Input
                                    size="large"
                                    value={loginForm.code}
                                    onChange={e =>
                                        setLoginForm({
                                            ...loginForm,
                                            code: e.target.value,
                                        })
                                    }
                                />
                                <div
                                    className="svg"
                                    onClick={refreshImgCode}
                                    dangerouslySetInnerHTML={{
                                        __html: codeInfo.svg,
                                    }}
                                ></div>
                            </div>
                        </Form.Item>
                        <div className={cssModule.remembermeWrap}>
                            <Checkbox
                                checked={isRemember}
                                onChange={checkboxChange}
                            >
                                记住密码
                            </Checkbox>
                        </div>
                        <div className={cssModule.btnWrap}>
                            <Button
                                type="primary"
                                size="large"
                                loading={loading}
                                onClick={submit}
                                block
                            >
                                登录
                            </Button>
                        </div>
                    </Form>
                </div>
            </div>
        </div>
    );
};
export default Login;
